/**
 * #info
 *@author
 *@createTime
 *@updateTime
 *@description  loading-bar  component   加载进度
 */

/**
 * #methodcomponent
 *
 * @type        aty-loading-bar
 * @cn          加载进度
 * @menu        工具
 */

import LoadingBar from './loading-bar.js'
let loadingBarInstance
// 进度条颜色
let color = 'primary'
// 错误时进度条的颜色
let failedColor = 'error'
// 进度条的高
let height = 2
let timer

/**
 * @description  获取进度条实例的方法
 * @returns {component}
 */
function getLoadingBarInstance () {
  loadingBarInstance = loadingBarInstance || LoadingBar.newInstance({
    color: color,
    failedColor: failedColor,
    height: height
  })

  return loadingBarInstance
}
/**
 *
 * @param options
 * @descriotion options
 */
function update (options) {
  // 获取实例
  const instance = getLoadingBarInstance()
  // 更新
  instance.update(options)
}

/**
 *@descriotion  隐藏
 */
function hide () {
  setTimeout(() => {
    update({
      show: false
    })
    setTimeout(() => {
      update({
        percent: 0
      })
    }, 200)
  }, 800)
}
// 清除定时器
function clearTimer () {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

export default {
  /**
   * @description  进度条开始
   */
  start () {
    if (timer) return
    let percent = 0
    update({
      percent: percent,
      status: 'success',
      show: true
    })
    timer = setInterval(() => {
      percent += Math.floor(Math.random() * 3 + 5)
      if (percent > 95) {
        clearTimer()
      }
      update({
        percent: percent,
        status: 'success',
        show: true
      })
    }, 200)
  },
  /**
   * @description  进度条更新
   */
  update (percent) {
    clearTimer()
    update({
      percent: percent,
      status: 'success',
      show: true
    })
  },
  /**
   * @description  进度条完成
   */
  finish () {
    clearTimer()
    update({
      percent: 100,
      status: 'success',
      show: true
    })
    hide()
  },
  /**
   * @description  进度条出错时的显示
   */
  error () {
    clearTimer()
    update({
      percent: 100,
      status: 'error',
      show: true
    })
    hide()
  },
  /**
   * @description  进度条参数配置
   */
  config (options) {
    if (options.color) {
      color = options.color
    }
    if (options.failedColor) {
      failedColor = options.failedColor
    }
    if (options.height) {
      height = options.height
    }
  },
  /**
   * @description  进度条销毁
   */
  destroy () {
    clearTimer()
    const instance = getLoadingBarInstance()
    loadingBarInstance = null
    // 实例销毁
    instance.destroy()
  }
}
